package com.example.rocketmq.controller;

import com.alibaba.fastjson.JSON;
import com.example.rocketmq.entity.Order;
import com.example.rocketmq.rocketmq.RocketMQProducer;
import com.example.rocketmq.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author kangshuai
 */
@Slf4j
@RestController
public class OrderController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RocketMQProducer producer;

    @Autowired
    private OrderService orderService;

    @PostMapping("/order/{productId}/{userId}")
    public String createOrder(@PathVariable(value = "productId") Integer productId,
                        @PathVariable(value = "userId") Integer userId) throws Exception {

        //比较库存
        Object stockNum = redisTemplate.opsForValue().get("product:stock:" + productId);
        if (Integer.parseInt(stockNum.toString()) <= 0) {
            return "库存不够了！";
        } else {
            Order order = new Order();
            order.setUserId(userId);
            order.setProductId(productId);

            producer.sendAsyncMsg(JSON.toJSONString(order));
        }

        return "生成订单成功";
    }

    @PostMapping("/order/pay/{orderId}}")
    public String payOrder(@PathVariable(value = "orderId") Integer orderId) throws Exception {
        orderService.payOrder(orderId);
        return "订单支付成功";
    }

    @GetMapping("/order/{orderId}")
    public Order getOrder(@PathVariable(value = "orderId") Integer orderId) throws Exception {
        Order order = orderService.findOne(orderId);
        return order;
    }
}
